package com.wql.service.impl;

import com.wql.dao.BookShopDao;
import com.wql.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.sql.SQLException;

/**
 * @author wql
 * @version 1.0
 * @date 2022/11/14 19:04
 */
@Service
public class BookShopServiceImpl implements BookShopService {
    @Autowired
    private BookShopDao bookShopDao;

    // Propagation.REQUIRES_NEW 一个事务进来运行完毕当即释放，接着运行另一事务挂起前一个事务，如果有异常进行回滚
    @Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED,
    rollbackFor = {SQLException.class, IOException.class},
    noRollbackFor = {ArithmeticException.class},
            timeout = 20
    )
    public void purchase(String isbn, String username) {
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        int stock = bookShopDao.findStockByIsbn(isbn);

        if(stock>0) {
            bookShopDao.updateBookStock(isbn);
        }else{
            throw new RuntimeException("图书编号为:"+isbn+";库存不足");
        }
        int balance = bookShopDao.findBalanceByUsername(username);

        if(balance>=price) {
            bookShopDao.updateAccount(username, price);
        }else{
            throw new RuntimeException("账户为:"+username+";余额不足.");
        }
    }
}
